package com.qjz.diancan.service.impl;


import com.qjz.diancan.exception.MyException;
import com.qjz.diancan.mapper.UserMapper;
import com.qjz.diancan.model.dto.LoginDto;
import com.qjz.diancan.model.entity.User;
import com.qjz.diancan.model.vo.common.ResultCodeEnum;
import com.qjz.diancan.service.UserService;
import com.qjz.diancan.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    //用户登录
    @Override
    public Map<String, Object> login(LoginDto loginDto)
    {
        System.out.println("loginDto = " + loginDto);
        String userName = loginDto.getUsername();
        User user = userMapper.selectUserInfoByUserName(userName);
        if (user == null) {
            throw new MyException(ResultCodeEnum.USER_NOT_EXISTS);
        }
        if (!user.getPassword().equals(loginDto.getPassword())) {
            throw new MyException(ResultCodeEnum.PASSWORD_ERROR);
        }
        // 2. 生成JWT令牌
        String token = JwtTokenUtil.generateToken(user.getUsername());
        Map<String, Object> response = new HashMap<>();
        response.put("user", user);
        response.put("token", token);
        return response;
    }


    @Override
    public void logout(String token){
//        JwtTokenUtil.re(token);
    }

    @Transactional
    @Override
    public void register(User user)
    {
        User user1 = userMapper.selectUserInfoByUserName(user.getUsername());
        if (user1 != null) {
            throw new MyException(ResultCodeEnum.USER_EXISTS);
        } else {
            userMapper.register(user);
        }
    }

    @Override
    public User getUserInfoByUserName(String username)
    {
        return userMapper.selectUserInfoByUserName(username);
    }
}